import { PlusOutlined } from '@ant-design/icons';
import { Button, Col, Divider, Form, message, Popconfirm, Row, Space, Switch, Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { IS_SUBAPP, useDrsState, useModel } from 'umi';

import { DeptTreeSelect } from '@szzj/drs-components';
import { SearchForm } from '@szzj/ds';

import useDataPerm from '@/hooks/useDataPerm';

import hooks from '../../hooks';

import type { IUserItem } from '@/types/permission/user';

export default () => {
  const { userInfo } = useDrsState();
  const { hasMenuAuthed } = useDataPerm(userInfo);
  const { hasPermisson } = useModel('watermarkModel');
  const {
    appCode,
    editHooks,
    tableForm,
    tableHooks: { tableProps, search },
    detailHooks,
    roleReq,
    onUpdateUserStatus,
    isAdmin,
    drsAppCode,
    updateUserStatusCode,
    roleDataType,
    isAreaPermission,
    postDelAppUserRequest,
  } = hooks.useContainer();
  const deletable = (row: IUserItem) => {
    if (IS_SUBAPP) {
      return row.hasDeletePerm;
    }
    return true;
  };

  const columns: ColumnsType<IUserItem> = [
    {
      title: '姓名',
      dataIndex: 'userName',
      width: 200,
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      width: 200,
      render: (value) => value ?? '-',
    },
    {
      title: '权限',
      render: (_, row) => {
        return row.deptRoleRequests.map((dept, index) => (
          <div key={index}>
            {dept.deptName}：
            <Space split={<Divider type="vertical" />} style={{ flexWrap: 'wrap' }}>
              {dept.roleList.map((role) => role.roleName)}
            </Space>
          </div>
        ));
      },
    },
    {
      title: '账号状态',
      width: 200,
      dataIndex: 'userStatus',
      render: (_, row) => {
        /** 用户中心，系统管理员；或业务系统，持有修改状态权限 */
        return updateUserStatusCode === '1' &&
          deletable(row) &&
          hasPermisson('USER_EDIT_STATUS') ? (
          <Switch
            checked={row.userStatus?.code === '1'}
            checkedChildren="启用"
            unCheckedChildren="禁用"
            onClick={(value) => {
              if (row.id) onUpdateUserStatus(row.id, value ? '1' : '0');
            }}
          />
        ) : (
          <Switch
            checked={row.userStatus?.code === '1'}
            checkedChildren="启用"
            unCheckedChildren="禁用"
            disabled
          />
        );
      },
    },
    {
      title: '操作',
      width: 150,
      align: 'right',
      fixed: 'right',
      render: (_, record) => {
        return (
          <Space>
            <Button
              type="link"
              disabled={!hasPermisson('USER_EDIT')}
              onClick={() => {
                if (record.superAdminFlag && !isAdmin) {
                  return message.info('非管理员，无权编辑管理员用户信息！');
                }
                editHooks.onOpen(record, true);
              }}
              style={{ padding: 0 }}
            >
              编辑
            </Button>
            <Button
              type="link"
              // disabled={!hasPermisson('USER_DETAIL')}
              onClick={() => {
                detailHooks.onOpen(record);
              }}
              style={{ padding: 0 }}
            >
              详情
            </Button>
            <Popconfirm
              disabled={!deletable(record) || !hasPermisson('USER_DEL')}
              title="删除后不可恢复，是否确认删除？"
              placement="topRight"
              okButtonProps={{ danger: true }}
              onConfirm={() => {
                if (!record?.userCode) {
                  return;
                }
                postDelAppUserRequest.run({
                  appCode,
                  userCode: record?.userCode,
                });
              }}
            >
              <Button
                type="link"
                danger
                style={{ padding: 0 }}
                disabled={!deletable(record) || !hasPermisson('USER_DEL')}
              >
                删除
              </Button>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];
  return (
    <>
      <SearchForm
        form={tableForm}
        onFinish={search.submit}
        submitter={false}
        layout="horizontal"
        style={{ paddingTop: 20 }}
      >
        <Row gutter={72}>
          <Col span={8}>
            <SearchForm.Input
              name="userName"
              label="姓名"
              style={{ width: '100%' }}
              normalize={(value: string) => value?.trim()}
              inputProps={{ maxLength: 20 }}
            />
          </Col>
          <Col span={8}>
            <SearchForm.Input
              name="userMobile"
              label="手机号"
              style={{ width: '100%' }}
              normalize={(value: string) => value?.trim()}
              inputProps={{ maxLength: 20 }}
            />
          </Col>
          <Col span={8}>
            <SearchForm.Select
              label="角色"
              name="roleCode"
              selectProps={{
                options: roleReq.data,
                fieldNames: {
                  label: 'roleName',
                  value: 'roleCode',
                },
                style: { width: '100%' },
              }}
            />
          </Col>
          <Col span={8}>
            <Form.Item
              label="部门"
              name="deptCode"
              initialValue={isAreaPermission ? userInfo?.currentDeptCode : undefined}
            >
              <DeptTreeSelect
                customDetailRequestUrl="/user/account/dept/detail"
                allowClear
                initDeptDeep={3}
                drsAppCode={drsAppCode}
                authed={hasMenuAuthed('/permission/user')}
                style={{ width: '100%' }}
                dropdownStyle={{
                  width: 300,
                }}
                isSubApp={IS_SUBAPP}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <SearchForm.Select
              label="帐号状态"
              name="userStatus"
              selectProps={{
                options: [
                  {
                    label: '禁用',
                    value: '0',
                  },
                  {
                    label: '启用',
                    value: '1',
                  },
                ],

                style: { width: '100%' },
              }}
            />
          </Col>
          <Col offset={16} span={8}>
            <Space style={{ float: 'right' }}>
              <Button
                type="primary"
                onClick={() => {
                  search.submit();
                }}
              >
                搜索
              </Button>
              <Button
                onClick={() => {
                  search.reset();
                }}
              >
                重置
              </Button>
            </Space>
          </Col>
        </Row>
      </SearchForm>
      <Button
        type="primary"
        icon={<PlusOutlined />}
        style={{ margin: '0 0 20px' }}
        disabled={!hasPermisson('USER_ADD')}
        onClick={() => {
          editHooks.onOpen(null, false);
        }}
      >
        新增用户
      </Button>

      <Table {...tableProps} columns={columns} rowKey="id" scroll={{ x: 900 }} />
    </>
  );
};
